
const record = require('./record')

class respManager {
    map = [];
    addHandler(handler){
        this.map[handler.command()] = handler;
   
    }

     
    
    onData(chunk){
        const buf = Buffer.from(chunk,"latin1");

	    console.log("buffer:");
	    console.log(buf);
	    console.log(buf.length);
        let offset = 0;
        const protocol = buf.readInt32LE(offset);
	    offset += 4;
        if((protocol+4) != buf.length){
	        console.log("error at buffer");
            return;
        }
        let command = buf.readInt16LE(offset);
	    offset += 2;
        
        console.log(command);
        if(command == 256){
        
            command = buf.readInt16LE(offset);
	        offset += 2;
        } 
        console.log(protocol);
        console.log(command);
        if(this.map[command] != undefined){
            console.log("!!!!");
            const handler = this.map[command];
            const raw = buf.slice(offset, buf.length); 
            const data =  handler.read(raw); 
            console.log(JSON.stringify(data));   
            record.insert(handler.type(), JSON.stringify(data))
           // console.log(this.map);
        }
        
    }
 
    onError(message){
    
    }
    result(){
        return 122222;
    }
}

module.exports = new respManager